package com.atsmart.app.webservice;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;

import android.os.Message;
import android.util.Log;

import com.atsmart.app.exception.BizException;
import com.google.json.Gson;
import com.google.json.JsonSyntaxException;
import com.google.json.stream.JsonReader;

public class ServiceHelper extends BaseService {
	private static final String TAG = "ServiceHelper";
	private static ServiceHelper instance = null;
	private Gson gson;

	public static synchronized ServiceHelper getInstance() {
		if (instance == null) {
			instance = new ServiceHelper();
		}

		return instance;
	}

	private ServiceHelper(){
		if (gson == null) {
			gson = new Gson();
		}
	}

	public <T> T getData(String url, Class<T> cls) throws JsonSyntaxException,
	           AssertionError, IOException, BizException,Exception {
		return (T) gson.fromJson(getFromService(url), cls);
	}

	@SuppressWarnings("unchecked")
	public <T> T getData(String url, Type type) throws JsonSyntaxException,
	           AssertionError, IOException, BizException {
		return (T)gson.fromJson(getFromService(url), type);
	}

	public <T> T postData(String url, String postString, Class<T> cls)
			throws JsonSyntaxException, AssertionError, IOException,
			BizException,Exception {
//		String postOnService = postOnService(url, postString);
//		Log.i(TAG, postOnService);
		return (T) gson.fromJson(postOnService(url, postString), cls);
	}

	@SuppressWarnings("unchecked")
	public <T> T postData(String url, String postString, Type type)
			throws JsonSyntaxException, AssertionError, IOException,
			BizException, Exception {
		return (T) gson.fromJson(postOnService(url, postString), type);
	}

	public <T> T postData(String url, String str1, String str2, Class<T> cls)
			throws JsonSyntaxException, AssertionError, IOException,
			BizException ,Exception{
		return (T) gson.fromJson(postOnService(url, str1, str2), cls);
	}

	public List<Message> readJsonStream(String url) {
		JsonReader reader = null;
		try {
			String jsonsString = getFromService(url);
			InputStream in = new ByteArrayInputStream(jsonsString.getBytes());
			reader = new JsonReader(new InputStreamReader(in,
					"UTF-8"));
			List<Message> messages = new ArrayList<Message>();
			reader.beginArray();
			while (reader.hasNext()) {
				Message message = gson.fromJson(reader, Message.class);
				messages.add(message);
			}
			reader.endArray();
			return messages;
		} catch (Exception e) {
			// TODO: handle exception
			return null;
		}
		finally{
			if (reader != null){
				try {
					reader.close();
				} catch (IOException e) {
				}
			}
		}
	}

	public String getSourceFromUrl(String linkUrl)
			throws MalformedURLException, IOException, BizException {
		return this.getFromService(linkUrl);
	}
}
